package ru.hh.team02.chat.server;

import ru.hh.team02.chat.database.*;
import ru.hh.team02.chat.client.Client;
import ru.hh.team02.chat.client.ClientRegistry;
import ru.hh.team02.chat.database.DatabaseServiceInterface;
import ru.hh.team02.chat.logger.SimpleLogger;
import ru.hh.team02.chat.messaging.SendingService;
import ru.hh.team02.chat.utils.ThreadPerTaskExecutor;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {
    private static final int PORT = 2004;

    private static final String[] ROOM_NAMES = { "r1", "r2" };

    public static final SimpleLogger ADMIN_LOGGER = new SimpleLogger(System.out);

    private static final ThreadPerTaskExecutor EXECUTOR = new ThreadPerTaskExecutor();

    public static ClientRegistry REGISTRY = new ClientRegistry(ROOM_NAMES);
    public static SendingService MESSENGER = new SendingService();
    public static DatabaseServiceInterface dbService = new SuperScalableNoSqlDbWithSharding();

    private ServerSocket listener = null;

    /*
     * listens to a port and spawns handlers
     */
    public void run() {
        try {
            listener = new ServerSocket(PORT);
            System.out.println("waiting for connection...");
            while (true) {
                try {
                    final Socket connection = listener.accept();
                    EXECUTOR.execute(new Client(connection));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            System.out.println("server went down");
            e.printStackTrace();
        } finally {
            try {
                if (listener != null) {
                    listener.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
